<?php


namespace app\index\service;


use app\common\GHttp;
use app\index\model\ToolsCount;
use GuzzleHttp\Exception\GuzzleException;
use Parsedown;
use think\Exception;
use think\exception\PDOException;
use think\facade\Cache;

class ScriptsService
{

    private $scriptUrl;
    private $scriptMdUrl;

    /**
     * Scripts constructor.
     * @throws Exception
     * @throws PDOException
     */
    public function __construct()
    {
//        $this->scriptUrl = sysconf('scriptUrl');
//        $this->scriptMdUrl = sysconf('scriptMdUrl');
        //github
//        $this->scriptUrl = "https://github.com/maxzhang666/OneKeyVip/raw/master/OneKeyVip.user.js";
//        $this->scriptMdUrl = "https://github.com/maxzhang666/OneKeyVip/raw/master/readme.md";
        //gitee
        $this->scriptUrl   = "https://gitee.com/ixysy/OneKeyVip/raw/master/OneKeyVip.user.js";
        $this->scriptMdUrl = "https://gitee.com/ixysy/OneKeyVip/raw/master/README.MD";
    }

    /**
     * 获取脚本内容
     * @return bool|string
     * @throws GuzzleException
     */
    public function getJs()
    {
        if (!empty($this->scriptUrl)) {
            $res = GHttp::get($this->scriptUrl, [], ['verify' => false]);
            return empty($res) ? false : $res;
        }
        return false;
    }

    /**
     * 获取描述
     * @return bool|string
     * @throws GuzzleException
     */
    public function getMd()
    {
        if (!empty($this->scriptMdUrl)) {
            $res = GHttp::get($this->scriptMdUrl, [], ['verify' => false]);
            return empty($res) ? false : $res;
        }
        return false;
    }

    public function parseMarkdown($markdown)
    {
        $mk = new Parsedown();
        return $mk->text($markdown);
    }

    /**
     * 获取meta
     * @param $jsContent
     * @return false|string
     */
    public function getMeta($jsContent)
    {
        return substr($jsContent, 0, stripos($jsContent, "(function"));
    }

    public function dataCount($isInstall, $ip)
    {
        $dateStr = date('Y-m-d', time());
        $opType  = $isInstall ? SCRIPT_INSTALL : SCRIPT_UPDATE;
        $key     = SCRIPT_KEY . "[{$opType}]_" . $ip;
        $flag    = Cache::get($key);
        if (!$flag) {
            $obj = ToolsCount::where(['date' => $dateStr, 'type' => $opType])->find();
            if (!$obj) {
                $obj       = new ToolsCount();
                $obj->num  = 1;
                $obj->date = $dateStr;
                $obj->type = $opType;
            } else {
                $obj->num = ['inc', 1];
            }
            $obj->save();
            Cache::set($key, true, 60 * 60 * 24);
        }
    }
}